package com.bci.pwtz.controller.app;

import javax.servlet.http.HttpServletRequest;

import com.bci.pwtz.mysql.model.Dyyhjrd;
import com.bci.pwtz.service.DyyhjrdService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bci.pwtz.common.DeviceDictConstants;
import com.bci.pwtz.common.PwtzConstants;
import com.bci.pwtz.common.remote.ListResponse;
import com.bci.pwtz.common.remote.ObjResponse;
import com.bci.pwtz.common.remote.ReturnCode;
import com.bci.pwtz.common.remote.req.DybxIdReq;
import com.bci.pwtz.common.remote.req.DybxListReq;
import com.bci.pwtz.common.remote.req.DybxReq;
import com.bci.pwtz.common.util.PaginationList;
import com.bci.pwtz.controller.AbstractController;
import com.bci.pwtz.exception.CanNotDeleteException;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.mysql.model.Dybx;
import com.bci.pwtz.service.DictionaryAuditService;
import com.bci.pwtz.service.DybxService;

import java.util.UUID;

/**
 * 低压表箱控制器类（PdbyqController）
 * TODO
 * 
 * @author ICLNetwork Team
 * @version 3.0
 */
@Controller
@RequestMapping("/api/dybx")
public class DybxAppController extends AbstractController
{
    // 自动扫描
    @Autowired
    private DybxService service;
    @Autowired
    DictionaryAuditService dictionaryAuditService;
    @Autowired
    DyyhjrdService dyyhjrdService;
    /**
     * 低压表箱的list查询
     * 一句话描述 <br/>
     * <p>Description: TODO(详细描述) 
     * <br/>
     * <p>Author: Administrator<br/>
     * <p>Date: 2014年9月25日-上午10:32:23<br/>
     * <p>
     * @param request
     * @return   
     *
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public ListResponse<Dybx> list(HttpServletRequest request)
    {
        DybxListReq req = null;
        ListResponse<Dybx> resp = new ListResponse<Dybx>();
        PaginationList<Dybx> list = new PaginationList<Dybx>();
        try
        {
            req = (DybxListReq) getJsonToObj(request, DybxListReq.class);
            if (req == null)
            {
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("请求为空");
                return resp;
            }
            if(req.getTimestamp() == null || req.getCompanyId() == null){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("参数错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (req.getSecretKey() == null)
            {
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥为空");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (!validateSecretKey(req.getSecretKey(), req.getTimestamp()))
            {
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (req.getUserId() == null)
            {
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("用户ID为空");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (StringUtils.isBlank(req.getToken()) || !validateToken(req.getToken(), req.getUserId()))
            {
                resp.setReturnCode(ReturnCode.TOKEN_INVALID);
                resp.setReturnMsg("票据无效");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            list = (PaginationList<Dybx>) service.findDybx(req.getDeviceName(), req.getCompanyId(), PwtzConstants.PORTAL_TYPE_APP, req.getMedLineCodes(),null,req.getBeginTime(), null, req.getPageSize(),req.getPage());
            if (list != null)
            {
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("查询低压表箱信息成功");
                resp.setTimestamp(req.getTimestamp());
                resp.setObjs(list);
            }else{
                resp.setReturnCode(ReturnCode.INTERFACE_INVOKE_ERROR);
                resp.setReturnMsg("查询低压表箱信息调用接口返回失败");
                resp.setTimestamp(req.getTimestamp());
            }
        }
        catch (PwtzDatabaseException e)
        {
            resp.setReturnCode(ReturnCode.DB_EXCEPTION);
            resp.setReturnMsg("数据库操作异常");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (Exception e)
        {
            resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
            resp.setReturnMsg("系统错误");
            resp.setTimestamp(req.getTimestamp());
        }
        return resp;
    }

    /**
     * 新增低压表箱信息
     * 一句话描述 <br/>
     * <p>Description: TODO(详细描述) 
     * <br/>
     * <p>Author: Administrator<br/>
     * <p>Date: 2014年9月25日-上午10:32:50<br/>
     * <p>
     * @param request
     * @return   
     *
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public ObjResponse<Dybx> add(HttpServletRequest request)
    {
    	DybxReq req = null;
        ObjResponse<Dybx> resp=new ObjResponse<Dybx>();
        try
        {
            req = (DybxReq) getJsonToObj(request, DybxReq.class);
            if (req == null)
            {
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("请求为空错误");
                return resp;
            }
            if(req.getObj() == null || req.getTimestamp() == null){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("参数错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (req.getSecretKey() == null)
            {
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥为空");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (!validateSecretKey(req.getSecretKey(), req.getTimestamp()))
            {
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (req.getUserId() == null)
            {
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("用户ID为空");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (StringUtils.isBlank(req.getToken()))
            {
                resp.setReturnCode(ReturnCode.TOKEN_INVALID);
                resp.setReturnMsg("票据为空");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (!validateToken(req.getToken(), req.getUserId()))
            {
                resp.setReturnCode(ReturnCode.TOKEN_INVALID);
                resp.setReturnMsg("票据无效");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            int result=0;
            Dybx rtObj = null;
            if(service.load(req.getObj().getDeviceid())!=null){
                result=service.update(req.getObj());
            }else{
                rtObj=service.add(req.getObj());
            }
            if (rtObj != null||result>0)
            {
                rtObj=service.load(req.getObj().getDeviceid());
                dictionaryAuditService.add(DeviceDictConstants.DYBX_MODEL_DICT_ID, rtObj.getModel());
                dictionaryAuditService.add(DeviceDictConstants.DYBX_MANUFACTURE_FACTORY_DICT_ID, rtObj.getProductionfactory());
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("新增低压表箱成功");
                rtObj.setLastoperatorid(req.getUserId());
                service.update(rtObj);
                resp.setTimestamp(req.getTimestamp());
                resp.setObj(rtObj);
                setLog(rtObj.getDeviceid(), rtObj.getCompanyid(), AbstractController.低压表箱, AbstractController.add, "新增低压表箱["+rtObj.getDevicename()+"]成功", req.getUserId());
//                //设置下户点
//                Dyyhjrd dyyhjrd=new Dyyhjrd();
//                dyyhjrd.setDeviceid(UUID.randomUUID().toString());
//                dyyhjrd.setDevicename(rtObj.getDevicename().replace("表箱","-接户线"));
//                dyyhjrd.setLongitude((Double.parseDouble(rtObj.getLongitude())+0.002)+"");
//                dyyhjrd.setLatitude(rtObj.getLatitude());
//                dyyhjrdService.add(dyyhjrd);
            }else{
                resp.setReturnCode(ReturnCode.INTERFACE_INVOKE_ERROR);
                resp.setReturnMsg("新增低压表箱调用接口返回失败");
                resp.setTimestamp(req.getTimestamp());
            }
        }
        catch (PwtzDatabaseException e)
        {
            resp.setReturnCode(ReturnCode.DB_EXCEPTION);
            resp.setReturnMsg("数据库操作异常");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (Exception e)
        {
            resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
            resp.setReturnMsg("系统错误");
            resp.setTimestamp(req.getTimestamp());
        }
        System.out.println(req.getObj());
        return resp;
    }

    /**
     * 修改低压表箱信息
     * 一句话描述 <br/>
     * <p>Description: TODO(详细描述) 
     * <br/>
     * <p>Author: Administrator<br/>
     * <p>Date: 2014年9月25日-上午10:33:25<br/>
     * <p>
     * @param request
     * @return   
     *
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public ObjResponse<Dybx> update(HttpServletRequest request)
    {
        DybxReq req = null;
        ObjResponse<Dybx> resp = new ObjResponse<Dybx>();
        int result = 0;
        try
        {
            req = (DybxReq) getJsonToObj(request, DybxReq.class);
            if (req == null)
            {
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("请求为空错误");
                return resp;
            }
            if(req.getObj() == null || req.getTimestamp() == null){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("参数错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (req.getSecretKey() == null)
            {
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥为空");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (!validateSecretKey(req.getSecretKey(), req.getTimestamp()))
            {
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (req.getUserId() == null)
            {
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("用户ID为空");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (StringUtils.isBlank(req.getToken()))
            {
                resp.setReturnCode(ReturnCode.TOKEN_INVALID);
                resp.setReturnMsg("票据为空");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (!validateToken(req.getToken(), req.getUserId()))
            {
                resp.setReturnCode(ReturnCode.TOKEN_INVALID);
                resp.setReturnMsg("票据无效");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            result = service.update(req.getObj());
            if (result > 0)
            {
                Dybx rtObj=service.load(req.getObj().getDeviceid());
                dictionaryAuditService.add(DeviceDictConstants.DYBX_MODEL_DICT_ID, req.getObj().getModel());
                dictionaryAuditService.add(DeviceDictConstants.DYBX_MANUFACTURE_FACTORY_DICT_ID, req.getObj().getProductionfactory());
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("修改低压表箱成功");
                rtObj.setLastoperatorid(req.getUserId());
                service.update(rtObj);
                resp.setObj(rtObj);
                resp.setTimestamp(req.getTimestamp());
                setLog(req.getObj().getDeviceid(), req.getObj().getCompanyid(), AbstractController.低压表箱, AbstractController.update, "修改低压表箱["+req.getObj().getDevicename()+"]成功", req.getUserId());
            }else{
                resp.setReturnCode(ReturnCode.INTERFACE_INVOKE_ERROR);
                resp.setReturnMsg("修改低压表箱调用接口返回失败");
                resp.setTimestamp(req.getTimestamp());
            }
        }
        catch (PwtzDatabaseException e)
        {
            resp.setReturnCode(ReturnCode.DB_EXCEPTION);
            resp.setReturnMsg("数据库操作异常");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (Exception e)
        {
            resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
            resp.setReturnMsg("系统错误");
            resp.setTimestamp(req.getTimestamp());
        }
        System.out.println(req.getObj());
        return resp;
    }

    /**
     * 删除低压表箱信息
     * 一句话描述 <br/>
     * <p>Description: TODO(详细描述) 
     * <br/>
     * <p>Author: Administrator<br/>
     * <p>Date: 2014年9月25日-上午10:33:35<br/>
     * <p>
     * @param requets
     * @return   
     *
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public ObjResponse<Dybx> delete(HttpServletRequest requets)
    {
        DybxIdReq req = new DybxIdReq();
        ObjResponse<Dybx> resp = new ObjResponse<Dybx>();
        int result = 0;
        try
        {
            req = (DybxIdReq) getJsonToObj(requets, DybxIdReq.class);
            if (req == null)
            {
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("请求为空错误");
                return resp;
            }
            if(req.getTimestamp() == null || req.getDeviceId() == null){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("参数错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (req.getSecretKey() == null)
            {
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥为空");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (!validateSecretKey(req.getSecretKey(), req.getTimestamp()))
            {
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (req.getUserId() == null)
            {
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("用户ID为空");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (StringUtils.isBlank(req.getToken()))
            {
                resp.setReturnCode(ReturnCode.TOKEN_INVALID);
                resp.setReturnMsg("票据为空");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (!validateToken(req.getToken(), req.getUserId()))
            {
                resp.setReturnCode(ReturnCode.TOKEN_INVALID);
                resp.setReturnMsg("票据无效");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            result = service.delete(req.getDeviceId());
            if (result > 0)
            {
                Dybx rtObj=service.load(req.getDeviceId());
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("删除低压表箱成功");
                rtObj.setLastoperatorid(req.getUserId());
                service.update(rtObj);
                resp.setTimestamp(req.getTimestamp());
                resp.setObj(rtObj);
                setLog(req.getDeviceId(), rtObj.getCompanyid(), AbstractController.低压表箱, AbstractController.delete, "删除低压表箱["+rtObj.getDevicename()+"]成功", req.getUserId());
            }else{
                resp.setReturnCode(ReturnCode.INTERFACE_INVOKE_ERROR);
                resp.setReturnMsg("删除低压表箱调用接口返回 失败");
                resp.setTimestamp(req.getTimestamp());
            }
        }
        catch (CanNotDeleteException e)
        {
            resp.setReturnCode(ReturnCode.DB_EXCEPTION);
            resp.setReturnMsg("存在依耐关系，不能删除");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (PwtzDatabaseException e)
        {
            resp.setReturnCode(ReturnCode.DB_EXCEPTION);
            resp.setReturnMsg("数据库操作异常");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (Exception e)
        {
            resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
            resp.setReturnMsg("系统错误");
            resp.setTimestamp(req.getTimestamp());
        }
        return resp;
    }
}